//
//  AccountSettingViewController.m
//  CPICMobileServiceApp
//
//  Created by sinosoft on 13-3-3.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "AccountSettingViewController.h"
#import  <QuartzCore/QuartzCore.h>
#import "DrawCode.h"
#import "RCAlertViewUtil.h"
#import "AppDelegate.h"
#import "ASIHTTPRequest.h"
#import "Config.h"
#import "NSString+SBJson.h"
#import "NSObject+SBJson.h"
#import "Config.h"
#import "RCAlertViewUtil.h"
#import "UIImageView+WebCache.h"

@interface AccountSettingViewController ()

@end

@implementation AccountSettingViewController
@synthesize TableViewUser;
@synthesize txtUserAccount,txtUserPassword,txtCodeIden;
@synthesize imgAccount;
@synthesize sinaAccount,qqAccount;
@synthesize QQopenId;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    NSUserDefaults *accountDefaults = [NSUserDefaults standardUserDefaults];
    NSString *bgimage= [accountDefaults objectForKey:@"UserDefaultBgKindKey"];
    
    if ([bgimage isEqualToString:@"蓝色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88@2x.png");
        ADD_LEFT_BUTTONITEM(@"back.png");
        //ADD_TITLE_NAMEITEM(@"账号绑定");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773@2x"]];
    }
    else if([bgimage isEqualToString:@"棕色主题风格"])
    {
        ADD_BACKGROUND_BUTTONITEM(@"icon640X88_01@2x.png");
        ADD_LEFT_BUTTONITEM(@"back_01.png");
        //ADD_TITLE_NAMEITEM(@"账号绑定");
        self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg640X773_01@2x"]];
    }
    else if([bgimage isEqualToString:@"重大节日皮肤"])
    {
        NSData *dataImg_02=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_02];
        NSLog(@"-------找到%@",dataImg_02);
        NSData *dataImg_03=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_03];
        NSData *dataImg_04=[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_DATA_04];
        
        NSURL *urlSkinImg_02=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_02]];
        NSURL *urlSkinImg_03=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_03]];
        NSURL *urlSkinImg_04=[NSURL URLWithString:[[NSUserDefaults standardUserDefaults]objectForKey:SKIN_IMG_URL_04]];
        NSLog(@"-------找到333%@",urlSkinImg_02);
        
        UIImageView * LogoImage = [[UIImageView alloc]init];
        [LogoImage setImageWithURL:urlSkinImg_03 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(LogoImage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_03];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        LogoImage.image = [UIImage imageWithData:dataImg_03];
        LogoImage.frame = CGRectMake(0, 0, LogoImage.image.size.width/2, LogoImage.image.size.height/2);
        [self.view addSubview:LogoImage];
        
        //--------------------------
        UIButton * CallOutBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
        CallOutBtn1.frame = CGRectMake(10, 10, 109/2, 57/2);
        UIImageView * Back = [[UIImageView alloc]init];
        [Back setImageWithURL:urlSkinImg_02 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(Back.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_02];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [Back setImage:[UIImage imageWithData:dataImg_02]];
        [CallOutBtn1 setImage:Back.image forState:UIControlStateNormal];
        [CallOutBtn1 addTarget:self action:@selector(ClickCallOutBtn) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:CallOutBtn1];
        //--------------------------
        
        //ADD_TITLE_NAMEITEM(@"账号绑定");
        
        UIImageView *bgimage = [[UIImageView alloc]initWithFrame:CGRectMake(0,44, self.view.frame.size.width, self.view.frame.size.height-44)];
        [bgimage setImageWithURL:urlSkinImg_04 success:^(UIImage *image)
         {
             NSData *imgData=UIImagePNGRepresentation(bgimage.image);
             [[NSUserDefaults standardUserDefaults] setObject:imgData forKey:SKIN_IMG_DATA_04];
         } failure:^(NSError *error)
         {
             [self justShowMessage:@"更新皮肤失败!" title:@"提示"];
         }];
        
        [bgimage setImage:[UIImage imageWithData:dataImg_04]];
        [self.view addSubview:bgimage];
        [bgimage release];
    }

    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=2;
    imgAccount=[[UIImageView alloc]initWithFrame:CGRectMake(25, 65, 72, 72)];
    //imgAccount.image=[UIImage imageNamed:@"qqLogo.png"];
    btnAuthorize=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    btnAuthorize.frame=CGRectMake(140, 75, 80, 50);
    [btnAuthorize setTitle:@"用户授权" forState:UIControlStateNormal];
    [btnAuthorize setBackgroundImage:[UIImage imageNamed:@"userAutho.png"] forState:UIControlStateNormal];
    [btnAuthorize addTarget:self action:@selector(AuthorizeBtnTap:) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:btnAuthorize];
    
    [self.view addSubview:imgAccount];
    mainview=[[DrawCode alloc]initWithFrame:CGRectMake(180, 3, 70, 31)];
    lable1=[[UILabel alloc]initWithFrame:CGRectMake(180, 3, 26, 25)];
    lable1.backgroundColor=[UIColor clearColor];
    lable2=[[UILabel alloc]initWithFrame:CGRectMake(119, 11, 26, 25)];
    lable2.backgroundColor=[UIColor clearColor];
    lable3=[[UILabel alloc]initWithFrame:CGRectMake(220, 7, 26, 25)];
    lable3.backgroundColor=[UIColor clearColor];
    lable4=[[UILabel alloc]initWithFrame:CGRectMake(240, 14, 26, 25)];
    lable4.backgroundColor=[UIColor clearColor];
    //添加UITableview
    TableViewUser = [[UITableView alloc]initWithFrame:CGRectMake(8, 150, 318, 280) style:UITableViewStyleGrouped];
	TableViewUser.delegate = self;
	TableViewUser.dataSource = self;
    
    TableViewUser.opaque = NO;
    TableViewUser.backgroundView = nil;
    TableViewUser.autoresizingMask = UIViewContentModeTop;
    TableViewUser.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    TableViewUser.scrollEnabled=NO;
    TableViewUser.backgroundColor=[UIColor clearColor];
    //[TableViewUser reloadData];
	[self.view addSubview:TableViewUser];
    
    btnRegister=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btnRegister setTitle:@"绑定" forState:UIControlStateNormal];
    [btnRegister setBackgroundImage:[UIImage imageNamed:@"userBind.png"] forState:UIControlStateNormal];
    btnRegister.frame=CGRectMake(70, 280, 200, 35);
    [btnRegister addTarget:self action:@selector(saveAccount) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:btnRegister];
    
    
    [mainview setBackgroundColor:[self getRandomColor]];
    pointArray = [[[NSMutableArray alloc]initWithCapacity:6]retain];
    [self getNumber];
    [self getLocation];
    
    
    _permissions = [[NSArray arrayWithObjects:
                     kOPEN_PERMISSION_GET_USER_INFO,
                     kOPEN_PERMISSION_GET_SIMPLE_USER_INFO,
                     kOPEN_PERMISSION_ADD_ALBUM,
                     kOPEN_PERMISSION_ADD_IDOL,
                     kOPEN_PERMISSION_ADD_ONE_BLOG,
                     kOPEN_PERMISSION_ADD_PIC_T,
                     kOPEN_PERMISSION_ADD_SHARE,
                     kOPEN_PERMISSION_ADD_TOPIC,
                     kOPEN_PERMISSION_CHECK_PAGE_FANS,
                     kOPEN_PERMISSION_DEL_IDOL,
                     kOPEN_PERMISSION_DEL_T,
                     kOPEN_PERMISSION_GET_FANSLIST,
                     kOPEN_PERMISSION_GET_IDOLLIST,
                     kOPEN_PERMISSION_GET_INFO,
                     kOPEN_PERMISSION_GET_OTHER_INFO,
                     kOPEN_PERMISSION_GET_REPOST_LIST,
                     kOPEN_PERMISSION_LIST_ALBUM,
                     kOPEN_PERMISSION_UPLOAD_PIC,
                     kOPEN_PERMISSION_GET_VIP_INFO,
                     kOPEN_PERMISSION_GET_VIP_RICH_INFO,
                     kOPEN_PERMISSION_GET_INTIMATE_FRIENDS_WEIBO,
                     kOPEN_PERMISSION_MATCH_NICK_TIPS_WEIBO,
                     nil] retain];
    NSString *appid = @"222222";
    _tencentOAuth = [[TencentOAuth alloc] initWithAppId:appid
											andDelegate:self];
}
-(void)AuthorizeBtnTap:(id)sender
{
    AppDelegate *appMyDelegate=[[UIApplication sharedApplication]delegate];
    appMyDelegate.iLoginorAccountTag=2;
    
    if (self.sinaAccount==YES && self.qqAccount==NO) {
        UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
        NSLog(@"%@", [keyWindow subviews]);
        
        
        [userInfo release], userInfo = nil;
        [statuses release], statuses = nil;
        
        SinaWeibo *sinaweibo = [self sinaweibo];
        
        if ([sinaweibo isAuthValid]) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你已经授权新浪微博" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"注销", nil];
            [alert show];
            [alert release];
            
        }
        else
        {
            [sinaweibo logIn];
        }

    }
    else if(self.qqAccount==YES && self.sinaAccount==NO)
    {
        [_tencentOAuth authorize:_permissions inSafari:NO];
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==1002) {
        if (buttonIndex==0) {
            
        }else if(buttonIndex==1)
        {
            [self setBindCancelRequest];
        }
        
    }else
    {
        SinaWeibo *sinaweibo = [self sinaweibo];
        if (buttonIndex==0) {
            
        }
        else if(buttonIndex==1)
        {
            [sinaweibo logOut];
        }
    }
}
- (SinaWeibo *)sinaweibo
{
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    return delegate.sinaweibo;
}
- (void)storeAuthData
{
    SinaWeibo *sinaweibo = [self sinaweibo];
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              sinaweibo.accessToken, @"AccessTokenKey",
                              sinaweibo.expirationDate, @"ExpirationDateKey",
                              sinaweibo.userID, @"UserIDKey",
                              sinaweibo.refreshToken, @"refresh_token", nil];
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"SinaWeiboAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self justShowMessage:@"授权成功" title:nil];
}
#pragma mark - SinaWeibo Delegate

- (void)sinaweiboDidLogIn:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogIn userID = %@ accesstoken = %@ expirationDate = %@ refresh_token = %@", sinaweibo.userID, sinaweibo.accessToken, sinaweibo.expirationDate,sinaweibo.refreshToken);
    [self storeAuthData];
}

- (void)sinaweiboDidLogOut:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboDidLogOut");
    
}

- (void)sinaweiboLogInDidCancel:(SinaWeibo *)sinaweibo
{
    NSLog(@"sinaweiboLogInDidCancel");
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo logInDidFailWithError:(NSError *)error
{
    NSLog(@"sinaweibo logInDidFailWithError %@", error);
}

- (void)sinaweibo:(SinaWeibo *)sinaweibo accessTokenInvalidOrExpired:(NSError *)error
{
    NSLog(@"sinaweiboAccessTokenInvalidOrExpired %@", error);
    
}

#pragma mark - SinaWeiboRequest Delegate

- (void)request:(SinaWeiboRequest *)request didFailWithError:(NSError *)error
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release], userInfo = nil;
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release], statuses = nil;
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post status \"%@\" failed!", postStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post status failed with error : %@", error);
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" failed!", postImageStatusText]
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        NSLog(@"Post image status failed with error : %@", error);
    }
    
    
    
}

- (void)request:(SinaWeiboRequest *)request didFinishLoadingWithResult:(id)result
{
    if ([request.url hasSuffix:@"users/show.json"])
    {
        [userInfo release];
        userInfo = [result retain];
    }
    else if ([request.url hasSuffix:@"statuses/user_timeline.json"])
    {
        [statuses release];
        statuses = [[result objectForKey:@"statuses"] retain];
    }
    else if ([request.url hasSuffix:@"statuses/update.json"])
    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
//                                                            message:[NSString stringWithFormat:@"Post status \"%@\" succeed!", [result objectForKey:@"text"]]
//                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alertView show];
        [alertView release];
        
        [postStatusText release], postStatusText = nil;
    }
    else if ([request.url hasSuffix:@"statuses/upload.json"])
    {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
//                                                            message:[NSString stringWithFormat:@"Post image status \"%@\" succeed!", [result objectForKey:@"text"]]
//                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:@"分享成功"
                                                           delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];        [alertView show];
        [alertView release];
        
        [postImageStatusText release], postImageStatusText = nil;
    }
    
}
- (void)storeAuthQQ
{
    
    NSDictionary *authData = [NSDictionary dictionaryWithObjectsAndKeys:
                              QQAccessToken, @"QQAccessToken",
                              QQopenId, @"QQopenId", nil];
    
    [[NSUserDefaults standardUserDefaults] setObject:authData forKey:@"Dict_QQAuthData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - TencentSessionDelegate
/**
 * Called when the user successfully logged in.
 */
- (void)tencentDidLogin {
	// 登录成功
	[self justShowMessage:@"QQ登录成功" title:nil];
    
    
    if (_tencentOAuth.accessToken
        && 0 != [_tencentOAuth.accessToken length])
    {
        QQAccessToken = _tencentOAuth.accessToken;
        QQopenId=_tencentOAuth.openId;
        [self storeAuthQQ];
    }
    else
    {
        QQAccessToken = @"登录不成功 没有获取accesstoken";
    }
    
}

/**
 * Called when the user dismissed the dialog without logging in.
 */
- (void)tencentDidNotLogin:(BOOL)cancelled
{
	if (cancelled){
        [self justShowMessage:@"用户取消登录" title:nil];
	}
	else {
        [self justShowMessage:@"登录失败" title:nil];
	}
	
}
/**
 * Called when the notNewWork.
 */
-(void)tencentDidNotNetWork
{
    [self justShowMessage:@"无网络连接，请设置网络" title:nil];
}

/**
 * Called when the logout.
 */
-(void)tencentDidLogout
{
    [self justShowMessage:@"退出登录成功，请重新登录" title:nil];
    QQAccessToken = @"";
    
    
}

-(void)setSinaItemTitle
{
    ADD_TITLE_NAMEITEM(@"新浪微博账户绑定");
}
-(void)setQQItemTitle
{
    ADD_TITLE_NAMEITEM(@"QQ账户绑定");
}
-(void) ClickCallOutBtn
{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(UIColor *)getRandomColor
{
    UIColor *color=[UIColor clearColor];
    switch ((arc4random()%5)) {
        case 0:
            color=[UIColor yellowColor];
            break;
        case 1:
            color=[UIColor redColor];
            break;
        case 2:
            color=[UIColor orangeColor];
            break;
        case 3:
            color=[UIColor cyanColor];
            break;
        case 4:
            color=[UIColor magentaColor];
            break;
        case 5:
            color=[UIColor purpleColor];
            break;
        default:
            
            break;
    }
    return  color;
}
-(void)getNumber
{
    for(NSInteger i = 0; i < 4; i++) //得到四个随机字符，取四次，可自己设长度
    {
        
        
        //int arr = arc4random() % 15+ 103;
        number = arc4random() % 9 + 0;
        switch (i) {
                
            case 0:
                lable1.text = [NSString stringWithFormat:@"%d",number];
                lable1.frame = CGRectMake(180, 3, lable1.frame.size.width, lable1.frame.size.height);
                break;
            case 1:
                lable2.text = [NSString stringWithFormat:@"%d",number];
                lable2.frame = CGRectMake(199, 11, lable2.frame.size.width, lable2.frame.size.height);
                break;
            case 2:
                lable3.text = [NSString stringWithFormat:@"%d",number];
                lable3.frame = CGRectMake(220, 7, lable3.frame.size.width, lable3.frame.size.height);
                break;
            case 3:
                lable4.text = [NSString stringWithFormat:@"%d",number];
                lable4.frame = CGRectMake(240, 14, lable4.frame.size.width, lable4.frame.size.height);
                
                break;
            default:
                break;
        }
    }
    
}
-(IBAction)PressDown:(id)sender
{
    [self getLocation];
    [self getNumber];
    [mainview setBackgroundColor:[self getRandomColor]];
}
- (void)getLocation
{
    [pointArray removeAllObjects];
    for(int j = 0; j<6; j++)
    {
        int pointx = arc4random() % 138;
        int pointy = arc4random() % 41;
        CGPoint point = CGPointMake(pointx, pointy);
        NSValue *points = [NSValue valueWithCGPoint:point];
        //CGPoint newPoint =[points CGPointValue];
        [pointArray addObject:points];
        
    }
    
    [mainview sharePoints:pointArray];
    [mainview setNeedsDisplay];
}
-(void)setBindCheckRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=62102";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    if (sinaAccount==NO && qqAccount==YES) {
        NSDictionary *dictQQInfo=[[NSUserDefaults standardUserDefaults] dictionaryForKey:@"Dict_QQAuthData"];
        if (dictQQInfo!=nil) {
            if ([dictQQInfo valueForKey:@"QQopenId"]) {
                NSLog(@"%@",[dictQQInfo valueForKey:@"QQopenId"]);
                QQopenId=[dictQQInfo valueForKey:@"QQopenId"];
            }
        }
        else
        {
        }
        if (QQopenId.length!=0) {
            [dicRequest setValue:QQopenId forKey:@"UserId"];
        }
        else
        {
            [dicRequest setValue:@"" forKey:@"UserId"];
        }
        [dicRequest setValue:@"2" forKey:@"bindingType"];
    }
    if (qqAccount==NO && sinaAccount==YES) {
        SinaWeibo *sinaweibo = [self sinaweibo];
        [dicRequest setValue:sinaweibo.userID forKey:@"UserId"];
        [dicRequest setValue:@"1" forKey:@"bindingType"];
    }
    [dicRequest setValue:@"" forKey:@"userAccount"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62102" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseBindCheckFail:)];
    [request setDidFinishSelector:@selector(ResonseBindCheckSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseBindCheckSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    NSString *strUserAccountQQSina=[dictResponse objectForKey:@"userAccount"];
    if (strUserAccountQQSina.length!=0) {
        TableViewUser.hidden=YES;
        btnAuthorize.hidden=YES;
        btnRegister.hidden=NO;
        imgAccount.hidden=YES;
        [btnRegister setTitle:@"解除绑定" forState:UIControlStateNormal];
        btnRegister.tag=2;
        [self justShowMessage:@"你的账号已经绑定本系统!" title:@"注意"];

    }
    else
    {
        TableViewUser.hidden=NO;
        btnAuthorize.hidden=NO;
        btnRegister.hidden=NO;
        imgAccount.hidden=NO;
        [btnRegister setTitle:@"绑定" forState:UIControlStateNormal];
        btnRegister.tag=1;
    }

    [strResult release];
    
    
}

- (void)ResponseBindCheckFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

-(void)saveAccount
{
    if (btnRegister.tag==2)
    {
        UIAlertView *myAlert=[[UIAlertView alloc]initWithTitle:@"注意" message:@"你确定要解除绑定吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        myAlert.tag=1002;
        [myAlert show];
        [myAlert release];
    }
    else 
    {
        if(txtUserAccount.text.length==0)
        {
            [self justShowMessage:@"用户账号不能为空" title:@"注意"];
            return;
        }
        if(txtUserPassword.text.length==0)
        {
            [self justShowMessage:@"用户密码不能为空" title:@"注意"];
            return;
        }
        
        [self setSinaQQRequest];
    }

}

-(void)setBindCancelRequest//向太保移动平台发送请求报文
{
    //    NSString *strRequestCode=@"RequestCode=62101";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    [dicRequest setValue:@"" forKey:@"UserAccount"];
    if (sinaAccount==YES) {
        SinaWeibo *sinaweibo = [self sinaweibo];
        if (sinaweibo.userID.length==0) {
            [self justShowMessage:@"你还没授权,请进行授权!" title:@"注意"];
            return;
        }
        [dicRequest setValue:sinaweibo.userID forKey:@"UserId"];
        [dicRequest setValue:@"1" forKey:@"bindingType"];
    }
    else if(qqAccount==YES)
    {
        if (QQopenId.length==0) {
            [self justShowMessage:@"你还没授权,请进行授权!" title:@"注意"];
            return;
        }
        [dicRequest setValue:@"2" forKey:@"bindingType"];
        [dicRequest setValue:QQopenId forKey:@"UserId"];
    }
    else
    {
        [dicRequest setValue:@"" forKey:@"UserId"];
    }
    
    [dicRequest setValue:txtUserPassword.text forKey:@"UserPassword"];
    [dicRequest setValue:txtCodeIden.text forKey:@"IdentifyingCode"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62103" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseBindCancelFail:)];
    [request setDidFinishSelector:@selector(ResonseSBindCaccelSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSBindCaccelSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    if ([strResult isEqualToString:@"1"]) {
        [self justShowMessage:@"成功解除绑定" title:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        NSString *strMessage=[dictHead objectForKey:@"message"];
        [self justShowMessage:strMessage title:nil];
    }
    [strResult release];
    
}

- (void)ResponseBindCancelFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}
#pragma UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

        static NSString *Identifier=@"Identifier";
        UITableViewCell *cell=(UITableViewCell *)[TableViewUser dequeueReusableCellWithIdentifier:Identifier];
        if (cell==nil)
        {
            cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier]autorelease];
            cell.accessoryType = UITableViewCellAccessoryNone;
            cell.selectionStyle=UITableViewCellSelectionStyleNone;//选中后颜色没变化
        }
        if(indexPath.row==0)
        {
            UILabel *lblUserAccount=[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 85, 21)];
            lblUserAccount.backgroundColor=[UIColor clearColor];
            lblUserAccount.text=@"用户账号:";
            [cell addSubview:lblUserAccount];
            [lblUserAccount release];
            
            txtUserAccount=[[UITextField alloc]initWithFrame:CGRectMake(100, 7, 197, 31)];
            txtUserAccount.delegate=self;
            txtUserAccount.borderStyle=UITextBorderStyleBezel;
            txtUserAccount.returnKeyType=UIReturnKeyDone;
            [cell addSubview:txtUserAccount];
        }
        else if(indexPath.row==1)
        {
            UILabel *lblUserName=[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 85, 21)];
            lblUserName.backgroundColor=[UIColor clearColor];
            lblUserName.text=@"用户密码:";
            [cell addSubview:lblUserName];
            [lblUserName release];
            
            txtUserPassword=[[UITextField alloc]initWithFrame:CGRectMake(100, 7, 197, 31)];
            txtUserPassword.delegate=self;
            txtUserPassword.borderStyle=UITextBorderStyleBezel;
            txtUserPassword.secureTextEntry=YES;
            txtUserPassword.returnKeyType=UIReturnKeyDone;
            [cell addSubview:txtUserPassword];
        }
        else if(indexPath.row==2)
        {
            UILabel *lblUserName=[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 85, 21)];
            lblUserName.backgroundColor=[UIColor clearColor];
            lblUserName.text=@"验证码:";
            [cell addSubview:lblUserName];
            [lblUserName release];
            
            txtCodeIden=[[UITextField alloc]initWithFrame:CGRectMake(80, 7, 90, 31)];
            txtCodeIden.delegate=self;
            txtCodeIden.borderStyle=UITextBorderStyleBezel;
            txtCodeIden.returnKeyType=UIReturnKeyDone;
            [cell addSubview:txtCodeIden];
            
            [cell addSubview:mainview];
            [cell addSubview:lable1];
            [cell addSubview:lable2];
            [cell addSubview:lable3];
            [cell addSubview:lable4];
            
            UIButton *btnChange=[UIButton buttonWithType:UIButtonTypeRoundedRect];
            [btnChange setTitle:@"换一张" forState:UIControlStateNormal];
            btnChange.frame=CGRectMake(257, 7, 50, 25);
            [btnChange addTarget:self action:@selector(changeBtnTag) forControlEvents:UIControlEventTouchDown];
            [cell addSubview:btnChange];
        }
    
    return cell;

}
-(void)changeBtnTag
{
    [self getLocation];
    [self getNumber];
    [mainview setBackgroundColor:[self getRandomColor]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if(textField==txtUserPassword)
    {
        [self SetAnimation:80];
    }
    else if(textField==txtCodeIden)
    {
        [self SetAnimation:110];
    }
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if(textField==txtUserPassword)
    {
        [self backAnimation:80];
    }
    else if(textField==txtCodeIden)
    {
        [self backAnimation:110];
    }
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField==txtUserAccount)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else if(textField==txtUserPassword)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else if(textField==txtCodeIden)
    {
        if(range.location>=20)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

-(void)SetAnimation:(CGFloat)Xorigin
{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    //frame.origin.x+=Xorigin;
    frame.origin.y-=Xorigin;
    //frame.size.height +=Xorigin;
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
}

-(void)backAnimation:(CGFloat)Xorigin
{
    NSTimeInterval animationDuration = 0.30f;
    CGRect frame = self.view.frame;
    //frame.origin.x -=Xorigin;
    frame.origin.y+=Xorigin;
    //frame.size.height -=Xorigin;
    self.view.frame = frame;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    self.view.frame = frame;
    [UIView commitAnimations];
    // [textField resignFirstResponder];
}
-(void)setSinaQQRequest//向太保移动平台发送请求报文
{
//    NSString *strRequestCode=@"RequestCode=62101";
    NSMutableDictionary *dicRequest = [NSMutableDictionary dictionary];
    [dicRequest setValue:self.txtUserAccount.text forKey:@"UserAccount"];
    if (sinaAccount==YES) {
        SinaWeibo *sinaweibo = [self sinaweibo];
        if (sinaweibo.userID.length==0) {
            [self justShowMessage:@"你还没授权,请进行授权!" title:@"注意"];
            return;
        }
        [dicRequest setValue:sinaweibo.userID forKey:@"UserId"];
        [dicRequest setValue:@"1" forKey:@"bindingType"];
    }
    else if(qqAccount==YES)
    {
        if (QQopenId.length==0) {
            [self justShowMessage:@"你还没授权,请进行授权!" title:@"注意"];
            return;
        }
        [dicRequest setValue:@"2" forKey:@"bindingType"];
        [dicRequest setValue:QQopenId forKey:@"UserId"];
    }
    else
    {
        [dicRequest setValue:@"" forKey:@"UserId"];
    }
    
    [dicRequest setValue:txtUserPassword.text forKey:@"UserPassword"];
    [dicRequest setValue:txtCodeIden.text forKey:@"IdentifyingCode"];
    NSString *strRequestJson=[dicRequest JSONRepresentation];
//    strRequestJson=[NSString stringWithFormat:@"&RequestData=%@",strRequestJson];
//    NSString *strUrl=[NSString stringWithFormat:@"%@%@%@",Server_Url,strRequestCode,strRequestJson];
//    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
//    NSURL *myurl = [NSURL URLWithString:strUrlEncod];//This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8.
//    NSLog(@"请求报文为:%@",strUrl);
    ASIFormDataRequest *request = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:Server_Url_Form]];
    //设置需要POST的数据，这里提交两个数据，A=a&B=b
    [request setPostValue:@"62101" forKey:@"RequestCode"];
    [request setPostValue:strRequestJson forKey:@"RequestData"];
    
    [request setDelegate:self];
    [request setDidFailSelector:@selector(ResponseSinaQQFail:)];
    [request setDidFinishSelector:@selector(ResonseSinaQQSuccess:)];
    [request startAsynchronous];
    
    showProgress = YES;
    if (showProgress) {
        NSLog(@"88888");
        // [NSThread sleepForTimeInterval:1];
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"查询中...";
        [progress show:YES];
        showProgress = NO;
    }
}

- (void)ResonseSinaQQSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    NSMutableDictionary *dictHead=[dictResponse valueForKey:@"head"];
    NSString *strResult= [[NSString alloc] initWithFormat:@"%@",[dictHead objectForKey:@"success"]];
    NSLog(@"strResult%@",strResult);
    if ([strResult isEqualToString:@"1"]) {
        [self justShowMessage:@"绑定成功" title:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }
    else
    {
        NSString *strMessage=[dictHead objectForKey:@"message"];
        [self justShowMessage:strMessage title:nil];
    }
    [strResult release];
    
}

- (void)ResponseSinaQQFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [self justShowMessage:@"服务器连接失败" title:@"注意"];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    [imgAccount release];
    [txtUserAccount release];
    [txtUserPassword release];
    [txtCodeIden release];
    [TableViewUser release];
    [super dealloc];
}

@end
